import { useState, useEffect } from "react";
import { Cascader, message } from "antd";
import { categoryGetOne, categoryGetTwo } from "@/api/modules/category";
import Cimage from "@/components/Cimage";
/** 商品分类级联选择器
 */
// 修复 `className` 缺少类型定义的问题，将其类型设置为 `string`，同时将 `onChange` 类型明确为更具体的函数类型
const Ccascader = ({
	value,
	onChange,
	className,
	disabled = false
}: {
	value?: number | null;
	onChange?: (selectedValue: number | string) => void;
	className?: string;
	disabled?: boolean;
}) => {
	interface Option {
		value: string | number;
		label?: React.ReactNode;
		text?: React.ReactNode;
		disabled?: boolean;
		children?: Option[];
		// 标记是否为叶子节点，设置了 `loadData` 时有效
		// 设为 `false` 时会强制标记为父节点，即使当前节点没有 children，也会显示展开图标
		isLeaf?: boolean;
	}
	const [categoryData, setCategoryData] = useState<Option[]>();

	// 初始化默认值
	const [defaultValue, setDefaultValue] = useState<(string | number)[]>([]);
	useEffect(() => {
		if (value && categoryData) {
			setDefaultValue(findCategoryPath(categoryData as any[], value as number));
		}
	}, [value, categoryData]);

	// 根据二级分类id categoryTwoId 查找分类路径
	function findCategoryPath(categories: any[], targetId: number) {
		if (!categories || categories.length === 0) {
			return [];
		}
		if (!targetId) {
			return [];
		}
		let defaultValue: any[] = [];
		categories.forEach(item => {
			if (item.children && item.children.length > 0) {
				item.children.forEach((child: { value: number }) => {
					if (child.value == targetId) {
						defaultValue = [item.value, child.value];
					}
				});
			}
		});
		return defaultValue;
	}
	// 获取分类数据
	async function getCategory() {
		try {
			// 获取所有分类数据
			const { data: categoryOne } = await categoryGetOne();
			const { data: categoryTwo } = await categoryGetTwo();

			let newCategoryData = categoryOne?.map(item => {
				const itemData: Option = {
					label: item.name,
					text: item.name,
					value: `s${item.id}`, // 防止父子id会造成冲突，故前缀加上 s+Id
					disabled: false,
					children: []
				};
				categoryTwo?.forEach(val => {
					if (item.id === val.parentId) {
						itemData.children?.push({
							// label: val.name,
							label: (
								<div className="flex items-center">
									{val.icon ? <Cimage src={val.icon[0].url} width={30} height={30} isPreview={false}></Cimage> : null}
									<span className="ml-5" data-testid="category-two-name">
										{val.name}
									</span>
								</div>
							),
							text: val.name,
							value: val.id,
							disabled: false
						});
					}
				});
				return itemData;
			});
			setCategoryData(newCategoryData);
		} catch (error) {
			console.error(error);
			message.error("获取分类数据失败");
		}
	}
	// 分类筛选回调
	const onCascaderChange = (value: (string | number)[]) => {
		console.log(value, "onCascaderChange");
		setDefaultValue(value);
		onChange && value && onChange(value[value.length - 1] as number);
		onChange && !value && onChange("");
	};
	useEffect(() => {
		getCategory();
	}, []);
	return (
		<Cascader
			className={className}
			disabled={disabled}
			// defaultValue={["zhejiang", "hangzhou", "xihu"]}
			value={defaultValue}
			options={categoryData}
			displayRender={(labels, selectedOptions) => labels.map((label, index) => selectedOptions![index].text).join(" / ")}
			expandTrigger="hover"
			onChange={(value: (string | number)[]) => onCascaderChange(value)}
			placeholder="商品类别"
		/>
	);
};

export default Ccascader;
